﻿using System;
using Microsoft.SharePoint;

namespace RSPDS.Core
{
    public static class RSPDS_Lists
    {
        public static SPListItemCollection Query(this SPList list, RSPDS_CamlBuilder.IRSPDS_Caml caml)
        {
            if (null == list) throw new ArgumentNullException("list");
            if (null == caml) throw new ArgumentNullException("caml");
            var query = new SPQuery { Query = RSPDS_CamlBuilder.GetQuery(caml) };
            return list.GetItems(query);
        }

        public static SPListItemCollection WhereField<T>(this SPList list, string fieldName, string valueType, string value) 
            where T:RSPDS_CamlBuilder.RSPDS_CamlCompare, new()
        {
            if (null == list) throw new ArgumentNullException("list");
            if (String.IsNullOrEmpty(fieldName)) throw new ArgumentNullException("fieldName");
            if (String.IsNullOrEmpty(valueType)) throw new ArgumentNullException("valueType");
            if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
            var caml = new T {FieldName = fieldName, ValueType = valueType, Value = value};
            return Query(list, caml);
        }

        public static void Iterate(this SPList list, Action<SPListItem> del)
        {
            if (null == list) throw new ArgumentNullException("list");
            if (null == del) throw new ArgumentNullException("del");
            // Iterate over all items in the list.
            var items = list.GetItems(new SPQuery {Query = "0"});
            for (var i = 0; i < list.ItemCount; i++)
                del(items[i]);
        }

        public static void Iterate(this SPList list, RSPDS_CamlBuilder.IRSPDS_Caml caml, Action<SPListItem> del)
        {
            if (null == list) throw new ArgumentNullException("list");
            if (null == del) throw new ArgumentNullException("del");
            if (null == caml) throw new ArgumentNullException("caml");
            // Iterate over all items in the list.
            var items = Query(list, caml);
            for (var i = 0; i < list.ItemCount; i++)
                del(items[i]);
        }
    }
}
